package jianli;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");//设置响应对象使用UTF-8编码
        request.setCharacterEncoding("UTF-8"); //设置请求对象使用UTF-8编码
        PrintWriter out = response.getWriter();//定义文本字符输出流
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>登录Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        String msg="";//声明后面要用到的字符串
        String username;
		String password;
		username = request.getParameter("username");
		password = request.getParameter("password");
        HttpSession session=request.getSession();//取得会话对象，没有就建一个
        //如果参数任意一个为空则失败
        if(username == null || username.equals("") || password==null || password.equals("")){
            msg = "用户名或密码为空，请<a href=login.jsp>重新登录</a>";
        }
        //如果用户名和密码不正确，也失败。这里规定用户名=wyj，密码=123
        else if(!username.equals("wyj") || !password.equals("123") ){
            msg = "用户名或密码错误，请<a href=login.jsp>重新登录</a>";
        }
        //登录成功，则打印登录成功信息
        else{
            session.setAttribute("username",username);
            response.setHeader("refresh","5;URL=WelcomeServlet");//定时跳转
            String s1="<h3>用户登录成功，5秒后跳转到欢迎页面!</h3><br>";
            String s2="<h3>如果没有跳转，请按<a href='WelcomeServlet'>这里</a></h3>";
            msg = s1+s2;
        }
        out.println(msg);
        out.println("</BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }
}